import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:universal_html/html.dart' as html;

import 'config.dart';
import 'log.dart';

/// [Bean] class maintains
class Bean {
  Bean({
    required this.id,
    required int networkType,
    this.aid = '',
    this.uin = '',
    this.ext1,
    this.ext2,
    this.ext3,
    String? version,
  }) {
    /// 若未设定[version]则从pubspec.yaml文件读取aegis version
    if (version == null || version == '') {
      _setAegisVersion();
    } else {
      version = version;
    }
    platform = _genPlatType();
    netType = networkType;
    sessionId = 'session-${DateTime.now().millisecondsSinceEpoch}';
  }

  /// id或者密钥标识符，用来分辨上报项目
  String id;

  /// 本地生成的唯一id
  String aid;

  /// 用户标示符号
  String uin;

  /// 本次上报的版本号码
  String version = '0';

  /// 网络类型
  late int netType;

  /// session id
  late String sessionId;

  /// 平台类型
  late int platform;

  /// [ext1] [ext2] [ext3] 为预留字段
  String? ext1;
  String? ext2;
  String? ext3;

  Future<void> _setAegisVersion() async {
    WidgetsFlutterBinding.ensureInitialized();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    version = packageInfo.version;
  }

  /// modify bean value from [Config] object
  void modifyValByConfig(Config config) {
    id = config.id;
    uin = config.uin ?? uin;
    aid = config.aid;
    version = config.version;
  }

  int _genPlatType() {
    if (kIsWeb) {
      return _configOSInsideWeb();
    } else if (Platform.isAndroid) {
      return PlatTypeNum.android.index;
    } else if (Platform.isIOS) {
      return PlatTypeNum.ios.index;
    } else {
      return PlatTypeNum.unknown.index;
    }
  }

  /// 在flutter-web场景下，需要区分iphone ipad ipod mac android windows等
  int _configOSInsideWeb() {
    final userAgent = html.window.navigator.userAgent.toString().toLowerCase();
    if (userAgent.contains("iphone") ||
        userAgent.contains("ipad") ||
        userAgent.contains("ipod")) {
      return PlatTypeNum.ios.index;
    }
    if (userAgent.contains("mac")) {
      return PlatTypeNum.macos.index;
    }
    if (userAgent.contains("android")) {
      return PlatTypeNum.android.index;
    }
    if (userAgent.contains("windows")) {
      return PlatTypeNum.windows.index;
    }
    if (userAgent.contains("linux")) {
      return PlatTypeNum.linux.index;
    }

    return PlatTypeNum.unknown.index;
  }

  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "aid": aid,
      "uin": uin,
      "version": version,
      "netType": netType,
      "ext1": ext1,
      "ext2": ext2,
      "ext3": ext3,
      'sessionId': sessionId,
      'platform': platform,
    };
  }

  @override
  String toString() {
    Map<String, dynamic> beanJson = toJson();

    return beanJson.keys.map((key) => '$key=${beanJson[key] ?? ''}').join('&');
  }
}
